package com.cwt_taxi_xa;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.cwt_taxi_xa.constants.Constants;
import com.cwt_taxi_xa.db.bll.LocalInfoBiz;
import com.cwt_taxi_xa.model.LocalInfo;
import com.cwt_taxi_xa.util.AppLog;
import com.cwt_taxi_xa.util.DateUtil;
import com.cwt_taxi_xa.util.ExceptionUtil;
import com.cwt_taxi_xa.util.StringUtil;
import com.cwt_taxi_xa.util.Tools;

import java.util.ArrayList;
import java.util.List;

/**
 * 收信箱信息界面
 *
 * @author ferch
 *
 */
public class CheckinDataList extends CWTBaseActivity implements OnScrollListener,OnTouchListener {
	private static final String TAG = "BusinessDataList";
	public TextView tips,tv_title;
	public ListView listView;
	public List<LocalInfo> list;
	public int currentPage = 1;// 默认第一页
	public static final int lineSize = 5;// 每次显示4条
	public int pageSize = 1; // 总多少页
	public int allRecord = 0;// 总记录
	private int lastItem;
	public View view;// 底部视图，加载更多
	TextView loadmore;
	public BusinessDataAdapter adapter;
	public static CheckinDataList instance;
	private LocalInfoBiz biz;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.checkin_data_list);

		biz = LocalInfoBiz.getInstance();
		view = getLayoutInflater().inflate(R.layout.loadmore, null);
		tips = (TextView) this.findViewById(R.id.q_tip);
		tv_title = (TextView) this.findViewById(R.id.tv_title);
		tv_title.setText("签到数据");
		listView = (ListView) this
				.findViewById(R.id.listView);
		listView.addFooterView(view);
		listView.setOnScrollListener(this);
		instance = CheckinDataList.this;
		// 获取总记录
		allRecord = biz.getBusinessCount();
		queryMessageCenter();
		adapter = new BusinessDataAdapter(this);
		// 获取总页数
		pageSize = (allRecord + lineSize - 1) / lineSize;
		loadmore = (TextView)view.findViewById(R.id.moreText);
		listView.setOnTouchListener(this);
		tips.setOnTouchListener(this);
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}

	/**
	 * 查找第一次的数据
	 */
	public void queryMessageCenter() {
		new AsyncTask<String, Integer, Long>() {
			@Override
			protected Long doInBackground(String... params) {
				ArrayList<LocalInfo> listCache = biz.getAllInfos(LocalInfo.TYPE_CHECK_IN, currentPage, lineSize);
				if(listCache != null && listCache.size() != 0){
					if(list == null){
						list = new ArrayList<LocalInfo>();
					}
					list.addAll(listCache);
				}
				return 1L;
			}

			@Override
			protected void onPostExecute(Long result) {
				if (list != null && list.size() > 0) {
					tips.setVisibility(View.GONE);
					adapter.setData(list);
					if(currentPage == 1){
						listView.setAdapter(adapter);
					}else{
						adapter.notifyDataSetChanged();
					}

					//把未读信息变为已读
					//						biz.updateMessageCenter();

					if (currentPage == pageSize) {
						listView.removeFooterView(view);
					}else{
						loadmore.setText(Constants.LOAD_MORE);
					}
				} else {
					tips.setText("暂无签到数据!");
					tips.setVisibility(View.VISIBLE);
				}
			}
		}.execute();
	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
						 int visibleItemCount, int totalItemCount) {
		lastItem = firstVisibleItem + visibleItemCount - 1; // 统计是否到最后
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		if (lastItem == adapter.getCount() && currentPage < pageSize
				&& scrollState == OnScrollListener.SCROLL_STATE_IDLE) {
			currentPage++;
			// 设置显示位置
			loadmore.setText(Constants.LOADING);
			listView.setSelection(lastItem);
			// 增加数据
			queryMessageCenter();
		}

	}

	/*class MyThread implements Runnable {
		@Override
		public void run() {

			while (timeta > 0) {

				if (timeta == 0) {
					break;
				}

				timeta--;
				Message message = new Message();
				message.what = 102;
				Bundle bl = new Bundle();
				bl.putInt("step", timeta);
				message.setData(bl);
				handler_refresh.sendMessage(message);
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					AppLog.e(ExceptionUtil.getInfo(e), e);
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}*/

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		return false;
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	public class BusinessDataAdapter extends BaseAdapter{
		private static final String TAG = "BusinessDataAdapter";
		public Context context;
		private LayoutInflater mInflater=null;
		private List<LocalInfo> list;
		private LocalInfo localInfo;

		public BusinessDataAdapter(Context context) {
			this.context = context;
			this.mInflater = LayoutInflater.from(context);
		}

		@Override
		public int getCount() {
			if(null!=list&&list.size()>0){
				return list.size();
			}

			return 0;
		}

		public void setData(List<LocalInfo> list) {
			this.list = list;
		}

		@Override
		public Object getItem(int arg0) {
			return list.get(arg0);
		}

		public void addItems(List<LocalInfo> nlist) {
			for (int i = 0; i < nlist.size(); i++) {
				this.list.add(nlist.get(i));
			}
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			try {

				ViewHolder viewHolder = null;
				if(convertView == null){
					convertView = mInflater.inflate(R.layout.checkin_day_item, null);
					viewHolder = new ViewHolder();
					viewHolder.tv_driver_code = (TextView) convertView.findViewById(R.id.tv_driver_code);
					viewHolder.tv_company_code = (TextView) convertView.findViewById(R.id.tv_company_code);
					viewHolder.tv_time = (TextView) convertView.findViewById(R.id.tv_time);
					viewHolder.tv_car_number = (TextView) convertView.findViewById(R.id.tv_car_number);
					viewHolder.tv_create_time = (TextView) convertView.findViewById(R.id.tv_create_time);
					convertView.setTag(viewHolder);
				}else{
					viewHolder = (ViewHolder) convertView.getTag();
				}
				localInfo = list.get(position);
				String data = localInfo.getData();
				byte[] dataContent = Tools.yxReversal(Tools.parseHexStr2Byte(data));

				int num = 0;
				num += 13+25;

				// 单位代码
				String company = Tools.byteToString(dataContent, num, 16);
				num += 16;
				// 从业资格证号
				String driverCode = Tools.byteToString(dataContent, num, 19);
				num += 19;
				// 车牌号
				String carNumber = Tools.byteToStringASCII(dataContent, num, 6);
				num += 6;
				// 计价器开机时间	YYYY-MM-DD-hh-mm
				String time = Tools.bcd2Str(Tools.byteTobyte(dataContent, num, 6));
				num += 6;
				time = DateUtil.getTime(time, DateUtil.df2, DateUtil.df11);
				String dataCreateTime = localInfo.getTime();
				if(!StringUtil.isNull(dataCreateTime)){
					String createTime = DateUtil.getTime("20"+dataCreateTime, DateUtil.df6, DateUtil.df1);
					createTime = DateUtil.getShowTime(createTime);
					viewHolder.tv_create_time.setText(createTime);
				}else{
					viewHolder.tv_create_time.setText("时间错误");
				}
				viewHolder.tv_company_code.setText(company);
				viewHolder.tv_driver_code.setText(driverCode);
				viewHolder.tv_car_number.setText(carNumber);
				viewHolder.tv_time.setText(time);
				return convertView;

			} catch (Exception e) {
				AppLog.e(ExceptionUtil.getInfo(e), e);
				e.printStackTrace();
				return null;
			}
		}
	}

	class ViewHolder{
		private TextView tv_driver_code;
		private TextView tv_company_code;
		private TextView tv_time;
		private TextView tv_car_number;
		private TextView tv_create_time;
	}

	@Override
	public void setStatus(int index, boolean status) {
		// TODO Auto-generated method stub

	}

	@Override
	public void sendMsg(int type, Object obj) {
		// TODO Auto-generated method stub

	}
}
